// pages/goods/intimatePurchaseDetail/intimatePurchaseDetail.js
const app = getApp()
import { requestApi } from '../../../api'
import { constants } from '../../../sdk/constants.js'
import { Uuid } from '../../../sdk/uuid.js'
import { formatPrice } from '../../../utils/util'
import { formatImage } from '../../../utils/formatImage'
import { formatTimeHMS } from '../../../utils/util'
import { colorSelect, specSelect } from '../../../templates/goodsSku/goodsSku'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    winWidth: 0,
    winHeight: 0,
    gid: '',
    uid: '',
    intimate_purchase_id: '',
    shareTitle: '',
    loading: false,
    colorStyle: 0,
    specStyle: 0,
    skuHidden: true,
    skuSpecId: '',     // 当前选中规格id
    shareCampaign: '',
    shareUtmTerm: '',
    shareUtmContent: '',
    shareUtmSearchKeyword: '',
    shareUtmTrafficSourceType: '',
  },
  checkOrderDetail: function (options) {
    let tradeNo = this.data.data.intimate_info.trade_no
    wx.navigateTo({
      url: '../../trade/tradeDetail/tradeDetail?trade_no=' + tradeNo,
    })

  },
  // 参加新的亲密购
  checkActivityList: function (options) {
    wx.navigateTo({
      url: '../../activity/activityList/activityList',
    })
  },
  // 立即购买 or 参加新的亲密购
  attendActivity: function () {
    if (!this.data.data.intimate_info.is_current_group && this.data.data.intimate_info.small_group_status == 2) { // 状态：拼团中2 && 没参加当前团0

      if (!app.toLogin()) {
        this.setData({
          loading: true
        })

        return false
      }
      
      this.setData({
        skuHidden: false
      })
    
    } else {
      wx.reLaunch({
        url: '../../activity/activityList/activityList',
      })
    }

  },

  toggleColor(e) {
    let currId = e.currentTarget.id
    let currSpecId = this.data.skuSpecId
    let skuList = this.data.data.goods_info.goods_sku
    let sizeList = this.data.data.goods_info.goods_size_list
    let result = colorSelect(currId, currSpecId, skuList, sizeList)

    this.setData({
      data: this.data.data,
      skuColorId: currId,
      colorStyle: currId,
      skuImage: result.skuImg,
      skuPrice: result.skuPrice,
      skuSpecVal: result.skuSpec,
      skuId: result.skuId,
    })
  },

  toggleSku(e) {
    if (!app.toLogin()) {
      this.setData({
        loading: true
      })

      return false
    }

    let skuFlag = this.data.skuHidden
    let skuPrice = this.data.data.goods_info.goods_price

    // 清除颜色规格的disabled
    for (let i = 0, len = this.data.data.goods_info.goods_color_list.length; i < len; i++) {
      this.data.data.goods_info.goods_color_list[i].noStock = false
    }

    for (let i = 0, len = this.data.data.goods_info.goods_size_list.length; i < len; i++) {
      this.data.data.goods_info.goods_size_list[i].noStock = false
    }
   
    this.setData({
      data: this.data.data,
      skuHidden: !skuFlag,
      skuPrice: skuPrice,
      colorStyle: 0,
      specStyle: 0,
    })
  },

  toggleSpec(e) {
    let currId = e.currentTarget.id
    let currColorId = this.data.skuColorId
    let skuList = this.data.data.goods_info.goods_sku
    let colorList = this.data.data.goods_info.goods_color_list
    let result = specSelect(currId, currColorId, skuList, colorList)

    this.setData({
      data: this.data.data,
      skuSpecId: currId,
      specStyle: currId,
      skuImage: result.skuImg,
      skuPrice: result.skuPrice,
      skuSpecVal: result.skuSpec,
      skuId: result.skuId,
    })
  },

  toConfirmPage() {
    if (!this.data.colorStyle || !this.data.specStyle) return false
    let url = '../goodsTrade/goodsTrade?sku_price=' + this.data.skuPrice + '&sku_spec=' + this.data.skuSpecVal + '&sku_id=' + this.data.skuId + '&gid=' + this.data.gid + '&activity_id=' + this.data.intimate_purchase_id + '&activity_type=3&sku_img=' + this.data.skuImage + '&chanel=' + this.data.channel
    wx.redirectTo({
      url: url,
    })
  },

  onLoad: function (options) {
    let gid = options.gid
    let intimate_purchase_id = options.intimate_purchase_id
    let data = {
      gid: gid,
      intimate_purchase_id: intimate_purchase_id
    }
    let utm_source = options.utm_source || ''
    let utm_share = options.utm_share || ''
    let utm_medium = options.utm_medium || ''
    let utm_term = options.utm_term || ''
    let utm_content = options.utm_content || ''
    let utm_campaign = options.utm_campaign || ''
    let utm_search_keyword = options.utm_search_keyword || ''
    let utm_traffic_source_type = options.utm_traffic_source_type || ''
    let shareUploadParams = {
      utm_source: utm_source,
      utm_share: utm_share,
      utm_medium: utm_medium,
      utm_term: utm_term,
      utm_content: utm_content,
      utm_campaign: utm_campaign,
      utm_search_keyword: utm_search_keyword,
      utm_traffic_source_type: utm_traffic_source_type,
    }

    // 埋点上报
    this.shareUpload(shareUploadParams)

    let systemInfo = {}

    try {
      systemInfo = wx.getSystemInfoSync()
    } catch (e) {
      // Do something when catch error
    }

    this.setData({
      winWidth: systemInfo.windowWidth,
      winHeight: systemInfo.windowHeight,
      shareUtmTerm: utm_term,
      shareUtmContent: utm_content,
      shareUtmSearchKeyword: utm_search_keyword,
      shareUtmTrafficSourceType: utm_traffic_source_type,
    })

    try {
      wx.setStorageSync('intimate', data)
    } catch (e) {

    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    if (!app.toLogin()) {
      this.setData({
        loading: true
      })
      return false
    } 
    
    wx.getStorage({
      key: 'intimate',
      success: (res) => {
        this.data.gid = res.data.gid,
        this.data.intimate_purchase_id = res.data.intimate_purchase_id
        this.getIntimatePurchaseDetail(res.data.gid, res.data.intimate_purchase_id)
      }
    })

    // 获取登录用户UID
    wx.getStorage({
      key: 'userinfo',
      success: (res) => {
        this.data.uid = res.data.uid
      },
    })
  },

  // 获取亲密购详情
  getIntimatePurchaseDetail(gid, intimate_purchase_id) {
    console.log(gid) 
    console.log(intimate_purchase_id)
    app.request({
      url: requestApi.intimatePurchaseDetailUrl,
      login: false,
      data: {
        gid: gid,
        intimate_purchase_id: intimate_purchase_id
      }
    }, (result) => {
      let res = this.getDetailCn(result)
      this.setData({
        data: res.original.data,
        loading: true,
        shareCampaign: res.original.data.utm_campaign,
      })

    }, (error) => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    })

  },

  // 亲密购详情内容转换
  getDetailCn(result) {
    if (result.original && result.original.data) {
      var data = result.original.data
      if (data.intimate_info) { // 亲密购信息
        if (data.intimate_info.user_list.length) {
          for (let i = 0; i < data.intimate_info.user_list.length; i++) {
            data.intimate_info.user_list[i]['path'] = formatImage.cdnImage(data.intimate_info.user_list[i]['path'], formatImage.THUMBNAIL_M)
          }
        }

        if (data.intimate_info.small_group_status == 2) {  // 拼团中有倒计时
          // data.content = '还有' + data.intimate_info.remain_orders + '</text>个名额'
          if (data.intimate_info.remain_time)  {
            let remainTime = data.intimate_info.remain_time
            let interval = setInterval(() => {
              let remainTip = formatTimeHMS(remainTime)
              remainTime = remainTime - 1
              this.setData({
                remainTip: remainTip,
              })

              if (remainTime < 0) {
                clearInterval(interval)
              }
            }, 1000)
          }
        }
      }

      if (data.goods_info) { // 商品信息
        data.goods_info.product_cover_image.path =
          data.goods_info.product_cover_image && data.goods_info.product_cover_image.path
            ? formatImage.cdnImage(data.goods_info.product_cover_image.path, formatImage.THUMBNAIL_M)
            : ''
        data.goods_info.goods_price = data.goods_info.goods_price ? formatPrice(data.goods_info.goods_price / 100) : 0
        data.goods_info.original_price = data.goods_info.original_price ? formatPrice(data.goods_info.original_price / 100) : 0
        data.goods_info.new_original_min_price = data.goods_info.original_min_price ? formatPrice(data.goods_info.original_min_price / 100) : 0
        data.goods_info.new_original_max_price = data.goods_info.original_max_price ? formatPrice(data.goods_info.original_max_price / 100) : 0
        data.goods_info.goods_channel_source_cn = data.goods_info.goods_channel_source ? this.getGoodsChannelSourceCn(data.goods_info.goods_channel_source) : ''
        if (data.goods_info.goods_sku.length) {
          for (let i = 0; i < data.goods_info.goods_sku.length; i++) {
            data.goods_info.goods_sku[i]['price'] = data.goods_info.goods_sku[i]['price']
              ? data.goods_info.goods_sku[i]['price'] / 100
              : 0

            data.goods_info.goods_sku[i]['goods_price'] = data.goods_info.goods_sku[i]['goods_price']
              ? data.goods_info.goods_sku[i]['goods_price'] / 100
              : 0
            data.goods_info.goods_sku[i]['goods_price_calculate'] = data.goods_info.goods_sku[i]['goods_price']

            if (data.goods_info.goods_sku[i]['image_list'].length) {
              for (let j = 0; j < data.goods_info.goods_sku[i]['image_list'].length; j++) {
                data.goods_info.goods_sku[i]['image_list'][j]['new_path'] = data.goods_info.goods_sku[i]['image_list'][j]['path']
                  ? formatImage.cdnImage(data.goods_info.goods_sku[i]['image_list'][j]['path'], formatImage.THUMBNAIL_M)
                  : ''
              }
            }
          }
        }

        data.share_title = '亲密购 | ' + data.goods_info.product_brandname_e + data.goods_info.final_level_type + '￥' + data.goods_info.goods_price

      }
      result.original.data = data
    }

    return result
  },
  
  getGoodsChannelSourceCn(source) {
    switch(source) {
      case 1:
        return '现货';
      case 2:
        return '现货';
      case 3:
        return '代购';
      case 4:
        return '现货';
    }

  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let gid = this.data.gid
    let intimate_purchase_id = this.data.intimate_purchase_id
    let utm_share = ''

    if (this.data.uid == '') {
      utm_share = constants.SOURCE + '_' + Uuid.get()
    } else {
      utm_share = constants.SOURCE + '_' + this.data.uid
    }

    return {
      title: this.data.data.share_title,
      path: '/pages/goods/intimatePurchaseDetail/intimatePurchaseDetail?gid=' + gid + '&intimate_purchase_id=' + intimate_purchase_id + '&channel=wx_xcx&utm_source=9_1&utm_share=' + utm_share + '&utm_medium=OFDearGroupViewController&utm_campaign=' + this.data.shareCampaign + '&utm_term=' + this.data.shareUtmTerm + '&utm_content=' + this.data.shareUtmContent + '&utm_search_keyword=' + this.data.shareUtmSearchKeyword + '&utm_traffic_source_type=' + this.data.shareUtmTrafficSourceType,
    }
  },

  /** 
   * 分享埋点数据上报
   */
  shareUpload: function (params) {
    app.request({
      url: requestApi.shareUploadLogUrl,
      method: 'POST',
      login: false,
      data: {
        utm_source: params.utm_source,
        utm_share: params.utm_share,
        utm_medium: params.utm_medium,
        utm_term: params.utm_term,
        utm_content: params.utm_content,
        utm_campaign: params.utm_campaign,
        utm_search_keyword: params.utm_search_keyword,
        utm_traffic_source_type: params.utm_traffic_source_type,
      },
    }, (data) => {
      console.log(data)
    }, (error) => {
      console.log(error)
    })
  },

})